package com.twt.scclientandroid03;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class BitmapServer extends Service {

	DataInputStream dis;
	Handler handler = new Handler();
	ThreadSendBroadcast tsb = null;
	boolean bool = true;
	Intent intent = null;
	int i = 0;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		System.out.println("onBind");
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		connect("192.168.1.198", 10000);
	}

	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		super.onRebind(intent);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		tsb = new ThreadSendBroadcast();
		tsb.run();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		return super.onUnbind(intent);
	}

	public boolean connect(String host, int port) {
		boolean fag = true;
		Log.i("twt","connect");
		try {
			Socket sock = new Socket(host, port);
			if(sock==null){
				Log.i("twt","sock is null");
				return false;
			}
			dis = new DataInputStream(sock.getInputStream());
		} catch (UnknownHostException ex) {
			fag = false;
		} catch (IOException ex) {
			fag = false;
		}
		return fag;
	}

	public byte[] readImageData() throws IOException {
		int len = dis.readInt();
		System.out.println(len + "");
		byte[] data = new byte[len];
		dis.readFully(data, 0, len);
		return data;
	}

	public void readServerSize() throws IOException {
		double width = 0, height = 0;
		width = dis.readDouble();
		height = dis.readDouble();
		// return new Dimension((int)width,(int)height);
	}

	public void showClientUI() throws IOException {
		if (bool) {
			readServerSize();
			intent = new Intent();
			intent.setAction("IMAGE_MESSAGE_ACTION");
			bool = false;
		}
		byte[] imageData = readImageData();
		intent.putExtra("IMAGE", imageData);
		sendBroadcast(intent);
	}

	class ThreadSendBroadcast implements Runnable {

		@Override
		public void run() {
			try {
				showClientUI();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.postDelayed(tsb, 0);
		}
	}
}
